#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"

//./Client server_ip server_port
static int sockfd = -1;
struct sockaddr_in server;

void Recv()
{
    // 接受服务器发来的数据
    while (true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        memset(&buffer, 0, sizeof(buffer));
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
}
void Send()
{
    while (true)
    {
        std::string input;
        std::cout << "Please Enter:";
        std::getline(std::cin, input);
        // 向服务器发送数据
        ssize_t ret = sendto(sockfd, input.c_str(), sizeof(input), 0, (struct sockaddr *)&server, sizeof(server));
        (void)ret;
    }
}
int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        std::cerr << "Usage:" << argv[0] << "server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    // 创建套接字：
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket fail!" << std::endl;
        return 2;
    }

    // 由服务器给客户端随机分配端口
    // 首次发送消息的时候，OS会自动给Clientbind
    // 客户端的端口是几不重要，唯一确定的就可以

    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // 创建两个线程，一个线程负责发消息，一个线程负责收消息

    Thread t2(Send);
    Thread t1(Recv);

    t1.Start();
    t2.Start();

    t1.join();
    t2.join();
    return 0;
}
